// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()
const db = cloud.database()
// 云函数入口函数
exports.main = async(event, context) => {
  const wxContext = cloud.getWXContext()
  const rst = await db.collection('personalInfo').where({
    _openid: wxContext.OPENID
  }).get();
  //console.log(rst)
  return await Promise.all(rst.data).then(res => {
    var tempdata = {
      _openid: wxContext.OPENID,
      name: "Saver",
      age: 18,
      sex: "secret",
      location: ["未知省", "未知市", "未知区"],
      signature: ''
    }
    //当读取不到该用户信息时自动创建新记录
    if (res.length == 0) {
      return db.collection("personalInfo").add({
        data: tempdata
      })
      .then(
        res => {
          //console.log(res)
          return tempdata
        }
      )
    } else { //否则，直接把查询到的数据返回
      return res[0]
    }
  })
  
}